package com.rzjm.api.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.lock.LockInfo;
import com.baomidou.lock.LockTemplate;
import com.baomidou.lock.executor.RedissonLockExecutor;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rzjm.api.constant.ResponseCode;
import com.rzjm.api.entity.*;
import com.rzjm.api.service.*;
import com.rzjm.api.util.DateUtil;
import com.rzjm.api.util.GsonResultBean;
import com.rzjm.api.util.OssUtil;
import com.rzjm.api.util.Tools;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 *@Author: ZhouWei
 *@Description:  动火作业
 *@Date 2018-05-10
 */
@Component
@RestController
@RequestMapping("/apply/shop/device/record")//url:模块/资源/{}/细分
public class ApplyShopDeviceRecordController extends BaseController {

    @Resource
    private UserService userService;
    @Resource
    private SysUserService sysUserService;
    @Resource
    private ApplyShopDeviceRecordService applyShopDeviceRecordService;
    @Resource
    private ShopService shopService;
    @Resource
    private LockTemplate lockTemplate;

    @Value("${web.uploadPath}")
    private String uploadPath;//图片地址
    @Value("${web.imgprefix}")
    private String imgPrefix;//图片地址

    /**
     *  通过id获取详情
     * @param
     * @throws Exception
     */
    @PostMapping(value = "/detail")
    public JSONObject view(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            logBefore(logger, "/apply/shop/device/record/detail 接收的参数： "+requestParam);
            System.out.println("/apply/shop/device/record/detail 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int record_id = jsonRequest.containsKey("record_id") ? jsonRequest.getInt("record_id") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            SysUser sysUser = sysUserService.selectByUniqueColumn("user_id",user.getSysUserId());
            if(sysUser == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您没有该权限"),true,true);
            }

            Shop shop = shopService.findById(sysUser.getShopId());
            if(shop == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您未绑定企业"),true,true);
            }
            ApplyShopDeviceRecord applyShopDeviceRecord = applyShopDeviceRecordService.findById(record_id);
            String deviceTypeName = "";
            if (applyShopDeviceRecord.getApplyDeviceType() != null){
                if (applyShopDeviceRecord.getApplyDeviceType().contains("2")){
                    deviceTypeName += ",油罐测温";
                }
                if (applyShopDeviceRecord.getApplyDeviceType().contains("1") ){
                    deviceTypeName += ",制粒机测温";
                }
                if (applyShopDeviceRecord.getApplyDeviceType().contains("3") ){
                    deviceTypeName += ",锅炉测温";
                }
                if (applyShopDeviceRecord.getApplyDeviceType().contains("4") ){
                    deviceTypeName += ",筒仓测量";
                }
                if (applyShopDeviceRecord.getApplyDeviceType().contains("5") ){
                    deviceTypeName += ",油罐测量";
                }
            }
            applyShopDeviceRecord.setApplyDeviceTypeStr(deviceTypeName.replaceFirst(",",""));
            map.put("record",applyShopDeviceRecord);
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",map),true,false);

        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     *  添加申请
     * @param
     * @throws Exception
     */
    @PostMapping(value="/add/record")
    public JSONObject addRecord(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;

        logBefore(logger, "/apply/shop/device/record/add/record 接收的参数： " + requestParam);
        System.out.println("/apply/shop/device/record/add/record 接收的参数： " + requestParam);
        JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
        int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
        if(user_id == 0){
            return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"请先登录！"),true,true);
        }
        LockInfo lockInfo = lockTemplate.lock(user_id + "_addApplyShopDeviceRecord", 30000L, 5000L, RedissonLockExecutor.class);
        if (lockInfo == null) {
            return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"业务处理中,请稍后再试"),true,true);
        }

        try{
            Date date = new Date();
            String dataJson = jsonRequest.containsKey("data_json") ? jsonRequest.getStr("data_json") : null;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            ApplyShopDeviceRecord applyShopDeviceRecord = JSONUtil.toBean(dataJson, ApplyShopDeviceRecord.class);
            applyShopDeviceRecord.setReqUserId(user_id);
            applyShopDeviceRecord.setCreateTime(date);
            Shop shop = null;
            try {
                shop = shopService.findById(applyShopDeviceRecord.getApplyShopId());
                if(shop == null){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该企业不存在"),true,true);
                }
                if(shop.getState() == 0){
                    System.out.println(shop.getShopName() + " 企业已被禁用");
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"企业已被禁用"),true,true);
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            applyShopDeviceRecord.setExamineSysUserId(shop.getFireChargeSysUserId());
            applyShopDeviceRecord.setApplyShopGroupId(shop.getGroupId());
            applyShopDeviceRecord.setApplyShopPianquId(shop.getPianquId());
            SysUser checkUser = sysUserService.findById(shop.getFireChargeSysUserId());
            if (checkUser == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该企业未设置生产经理，不能申请"),true,true);
            }
            applyShopDeviceRecord.setExamineSysUserName(checkUser.getName());
//            applyShopDeviceRecord.setEffectTime(DateUtil.getAfterDateMinuteByDate(date,30));

            boolean ret = applyShopDeviceRecordService.save(applyShopDeviceRecord);
            if(ret){
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功"),true,true);
            }else{
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"失败"),true,true);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     *  申请列表
     * @param
     * @throws Exception
     */
    @PostMapping(value = "/my/list")
    public JSONObject myRegList(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            logBefore(logger, "/apply/shop/device/recordk/my/list 接收的参数： "+requestParam);
            System.out.println("/apply/shop/device/record/my/list 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int pageIndex = jsonRequest.containsKey("page_index") ? jsonRequest.getInt("page_index") : 1;
            int pageSize = jsonRequest.containsKey("pageSize") ? jsonRequest.getInt("pageSize") : 10;
            int state = jsonRequest.containsKey("state") ? jsonRequest.getInt("state") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            SysUser sysUser = sysUserService.selectByUniqueColumn("user_id",user.getSysUserId());
            if(sysUser == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您没有该权限"),true,true);
            }
            QueryWrapper<ApplyShopDeviceRecord> qw = new QueryWrapper<>();
            if (sysUser.getUserType() < 2){

            }else if (sysUser.getUserType() == 2){
                qw.eq("apply_shop_group_id", sysUser.getGroupId());
            }else if (sysUser.getUserType() == 3){
                qw.eq("apply_shop_pianqu_id", sysUser.getPianquId());
            }else {
                qw.eq("apply_shop_id", sysUser.getShopId());
            }

            qw.eq("examine_state", state);
            List<ApplyShopDeviceRecord> list = applyShopDeviceRecordService.getPageEntityList(qw,pageIndex,pageSize);
            list.stream().map(a -> {
                String deviceTypeName = "";
                if (a.getApplyDeviceType() != null){
                    if (a.getApplyDeviceType().contains("2")){
                        deviceTypeName += ",油罐测温";
                    }
                    if (a.getApplyDeviceType().contains("1") ){
                        deviceTypeName += ",制粒机测温";
                    }
                    if (a.getApplyDeviceType().contains("3") ){
                        deviceTypeName += ",锅炉测温";
                    }
                    if (a.getApplyDeviceType().contains("4") ){
                        deviceTypeName += ",筒仓测量";
                    }
                    if (a.getApplyDeviceType().contains("5") ){
                        deviceTypeName += ",油罐测量";
                    }
                }
                a.setApplyDeviceTypeStr(deviceTypeName.replaceFirst(",",""));
                if (a.getExamineSysUserId() != null && a.getExamineSysUserId().intValue() == sysUser.getUserId().intValue()){
                    a.setIsCanCheck(1);
                }else {
                    a.setIsCanCheck(0);
                }
                return a;
            }).collect(Collectors.toList());
            map.put("records",list);
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",list.size(),map),false,false);

        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     *  申请列表
     * @param
     * @throws Exception
     */
    @PostMapping(value = "/my/apply")
    public JSONObject myApply(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            logBefore(logger, "/apply/shop/device/recordk/my/apply 接收的参数： "+requestParam);
            System.out.println("/apply/shop/device/record/my/apply 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int pageIndex = jsonRequest.containsKey("pageIndex") ? jsonRequest.getInt("pageIndex") : 1;
            int pageSize = jsonRequest.containsKey("pageSize") ? jsonRequest.getInt("pageSize") : 10;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }
            Date date = new Date();
            QueryWrapper<ApplyShopDeviceRecord> qw = new QueryWrapper<>();
            qw.eq("req_user_id", user_id);
            qw.orderByDesc("create_time");
//            qw.last("limit 1");
            List<ApplyShopDeviceRecord> list = applyShopDeviceRecordService.getPageEntityList(qw,pageIndex,pageSize);

            if (list != null && list.size() > 0){
                list.stream().map(a -> {
                    if(a.getExamineState() != null && a.getEffectTime() != null && a.getExamineState() == 1 && a.getEffectTime().compareTo(date) > 0){
                        a.setIsEffective(1);
                    }else {
                        a.setIsEffective(0);
                    }
                    String deviceTypeName = "";
                    if (a.getApplyDeviceType() != null){
                        if (a.getApplyDeviceType().contains("2")){
                            deviceTypeName += ",油罐测温";
                        }
                        if (a.getApplyDeviceType().contains("1") ){
                            deviceTypeName += ",制粒机测温";
                        }
                        if (a.getApplyDeviceType().contains("3") ){
                            deviceTypeName += ",锅炉测温";
                        }
                        if (a.getApplyDeviceType().contains("4") ){
                            deviceTypeName += ",筒仓测量";
                        }
                        if (a.getApplyDeviceType().contains("5") ){
                            deviceTypeName += ",油罐测量";
                        }
                    }
                    a.setApplyDeviceTypeStr(deviceTypeName.replaceFirst(",",""));
                    return a;
                }).collect(Collectors.toList());
            }
            map.put("records",list);
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",list.size(),map),false,false);

        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 电焊机设备 生产经理审批
     * @param
     * @throws Exception
     */
    @PostMapping(value="/check")
    @ResponseBody
    public JSONObject managerCheckRecord(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        logBefore(logger, "/apply/shop/device/record/check接收的参数： " + requestParam);
        System.out.println("/apply/shop/device/record/check接收的参数： " + requestParam);
        JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
        int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
        LockInfo lockInfo = lockTemplate.lock(user_id + "_applyManagerCheckRecord", 30000L, 5000L, RedissonLockExecutor.class);
        if (lockInfo == null) {
            return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"业务处理中,请稍后再试"),true,true);
        }
        try{
            int record_id = jsonRequest.containsKey("record_id") ? jsonRequest.getInt("record_id") : 0;
            int check_state = jsonRequest.containsKey("check_state") ? jsonRequest.getInt("check_state") : 0;
//            String check_result = jsonRequest.containsKey("check_result") ?jsonRequest.getStr("check_result") : "";

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户信息不存在"),true,true);
            }



            SysUser sysUser = sysUserService.selectByUniqueColumn("user_id",user.getSysUserId());
            if(sysUser == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您没有审核权限"),true,true);
            }


            ApplyShopDeviceRecord record = applyShopDeviceRecordService.findById(record_id);
            if(record == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该申请不存在"),true,true);
            }


            Shop shop = null;
            try {
                shop = shopService.findById(record.getApplyShopId());
                if(shop == null){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该企业不存在"),true,true);
                }
                if(shop.getState() == 0){
                    System.out.println(shop.getShopName() + " 企业已被禁用");
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"企业已被禁用"),true,true);
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }


            if(record.getExamineSysUserId().intValue() != sysUser.getUserId().intValue()){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"暂无权限"),true,true);
            }

            try{
                Date date = new Date();
                record.setExamineState(check_state);
                record.setExamineTime(date);
                record.setExamineUserId(user_id);
//                record.setExamineSysUserId(sysUser.getUserId());
                if(check_state == 2){
                    // 审核通过30分钟有效期
                    record.setEffectTime(DateUtil.getAfterDateMinuteByDate(date, 30));
                }
                record.setEffectTime(DateUtil.getAfterDateMinuteByDate(date, 30));
                boolean ret = applyShopDeviceRecordService.updateById(record);
                if(ret){
                    result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"审核成功"),true,true);
                }else{
                    result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"审核失败"),true,true);
                }
            }catch (Exception e){
                e.printStackTrace();
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常"),true,true);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }finally {
            //释放锁
            lockTemplate.releaseLock(lockInfo);
        }
        return result;
    }

    /**
     *   我的企业列表
     * @param
     * @throws Exception
     */
    @RequestMapping(value="/my/shop/list",method = {RequestMethod.POST},produces="application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject myList(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            logBefore(logger, "接收的参数： " + requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 1;
            int shop_type = jsonRequest.containsKey("shop_type") ? jsonRequest.getInt("shop_type") : 0;
            int device_type = jsonRequest.containsKey("device_type") ? jsonRequest.getInt("device_type") : 0;
            int pageIndex = jsonRequest.containsKey("pageIndex") ? jsonRequest.getInt("pageIndex") : 1;
            int pageSize = jsonRequest.containsKey("pageSize") ? jsonRequest.getInt("pageSize") : 10;
            String keyword = jsonRequest.containsKey("keyword") ? jsonRequest.getStr("keyword") : "";
            int position = jsonRequest.containsKey("position") ? jsonRequest.getInt("position") : 10;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户信息不存在"),true,true);
            }

            List<Shop> list = shopService.selectApplyMyList(user,1, keyword, shop_type, device_type,position, pageIndex, pageSize);
            map.put("shops",list);
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",list.size(),map),false,false);
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(-1,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }
}
